package com.bilibili.manage;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.bilibili.exception.BusinessException;
import com.bilibili.utils.RandomUtils;
import com.bilibili.utils.RedisOperations;
import com.bilibili.vo.AliPayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.Date;

import static com.bilibili.constant.BusinessConstant.REDIS_ORDER_ID_INCR_KEY;

/**
 * 阿里第三方支付
 *
 * @Author YM
 */
@Component
public class AliPayService {
    @Autowired
    private RedisOperations redisOperations;
    @Value("${ali.appId}")
    private String appId;
    @Value("${ali.merchantPrivateKey}")
    private String merchantPrivateKey;
    @Value("${ali.alipayPublicKey}")
    private String alipayPublicKey;

    public AlipayTradePagePayResponse payOrder(AliPayVo aliPayVo) {
        String subject = aliPayVo.getSubject();
        String outTradeNo = RandomUtils.getOrderIdOrefix(new Date()) + String.format("%1$08d", redisOperations.incr(REDIS_ORDER_ID_INCR_KEY));
        String totalAmount = aliPayVo.getTotalAmount();
        String returnUrl = aliPayVo.getReturnUrl();

        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions());
        // 2. 发起API调用（以创建当面付收款二维码为例）
        AlipayTradePagePayResponse response = null;
        try {
            response = Factory.Payment.Page()
                    .pay(subject, outTradeNo, "15", returnUrl);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(HttpStatus.BAD_REQUEST, "支付异常");
        }
        return response;
    }

    private Config getOptions() {
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = "openapi.alipaydev.com";
        config.signType = "RSA2";
        config.appId = appId;
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        config.merchantPrivateKey = merchantPrivateKey;
        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        config.alipayPublicKey = alipayPublicKey;
        return config;
    }
}
